package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import delegate.BusinessDelegate;
import dtos.VentaDTO;
import entities.ItemVenta;

/**
 * Servlet implementation class ConfirmarVenta
 */
@WebServlet("/ConfirmarVenta")
public class ConfirmarVenta extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConfirmarVenta() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String operacion = (String)request.getParameter("operacion");
		HttpSession session = request.getSession();
		
		try {
			if(operacion.equals("cancelar")){
				BusinessDelegate.getInstancia().cancelar();
			
			}else if (operacion.equals("compra")){
				 VentaDTO venta = BusinessDelegate.getInstancia().confirmarVenta();
				 if (venta!=null){
					 response.getWriter().write("monto total: " + venta.getMontoTotal());
					 List<ItemVenta> items = new ArrayList<ItemVenta>();
					 session.removeAttribute("itemsCarrito");
					 session.setAttribute("itemsCarrito", items);
				 }
			}
		} catch (NamingException e) {
			e.printStackTrace();
			request.setAttribute("error", "Naming Exception");
			dispatch("/error.jsp", request, response);
		}
	}

	protected void dispatch(String jsp, HttpServletRequest request,	HttpServletResponse response) throws ServletException, IOException
	{
		if ( jsp != null )
		{
			RequestDispatcher rd = request.getRequestDispatcher(jsp);
			rd.forward(request, response);
		}
	}

}
